<?php
$basePath = dirname(__FILE__).'/';
include_once $basePath.'config.php';
include_once $basePath.'greatiful_con.php';

$method = isset($_GET['method'])?$_GET['method']:'';
$token = isset($_GET['token'])?$_GET['token']:null;
$verifier = isset($_GET['verifier'])?$_GET['verifier']:null;

$gf = new Greatiful($token, $verifier);
$post = array();
if ($_POST) {
	foreach ($_POST as $index => $val) {if ($val && $index) $post[$index] = $val;}
}


if ($method) {
    $result = false;
    switch ($method) {
	case 'userInfo':
	    if ($result = $gf->getMethod(array('user', 'info'))) {
		jsonResponse('OK', $result);
	    }
	    break;
	case 'userAccount':
	    if ($result = $gf->getMethod(array('user', 'account'))) {
		jsonResponse('OK', $result);
	    }
	    break;
	case 'readerList':
	    if ($result = $gf->getMethod(array('reader', 'list'))) {
		jsonResponse('OK', $result);
	    }
	    break;
	case 'channelsList':
		if ($result = $gf->getMethod(array('channels', 'list'), $post)) {
		jsonResponse('OK', $result);
	    }
	    break;
	case 'channelItems':
       		if ($result = $gf->getMethod(array('channels', $_GET['cid'], 'items'), $post)) {
       		jsonResponse('OK', $result);
       	    }
       	    break;
	case 'readerSubscribe':
                if ($result = $gf->postMethod(array('reader', 'subscribe'), $post)) {
                jsonResponse('OK', $result);
		}
		break;	
	case 'readerUnsubscribe':
		if ($result = $gf->deleteMethod(array('reader', 'unsubscribe'), $post)) {
                jsonResponse('OK', $result);
                }
                break;
	case 'categoryList':
		if ($result = $gf->getMethod(array('user', 'category', 'list'), $post)) {
                jsonResponse('OK', $result);
                }
		print_r($gf->getLastResponseInfo());
                break;
     	case 'authUrl':
	    jsonResponse('OK', $result = $gf->getAuthorizeUrl());
	    break;
    }
    if ($gf->getError() == GF_ERR_NONAUTHORIZED) {
	jsonResponse('AUTH', $result = $gf->getAuthorizeUrl());
    } else {
        jsonResponse('BAD', 'wrong');
    }
}

jsonResponse('AUTH', $result = $gf->getAuthorizeUrl());

function jsonResponse($status, $result) {
    echo json_encode(array('status' => $status, 'result' => $result));
    die();
} 
